/**
 * AI功能IPC处理器
 * 连接前端与AI服务
 */

import { ipcMain } from 'electron'
import { EnhancedLangChainService } from '../services/EnhancedLangChainService'
import { log } from '../utils/Logger'

// 创建增强的LangChain服务实例
let aiService: EnhancedLangChainService | null = null

// 初始化AI服务
async function initializeAIService(): Promise<EnhancedLangChainService> {
  if (!aiService) {
    aiService = new EnhancedLangChainService()
    await aiService.initialize()
    log.ai('AI Service initialized successfully')
  }
  return aiService
}

// 注册AI相关的IPC处理器
export function registerAIHandlers(): void {
  // AI写作功能
  ipcMain.handle('ai:polish', async (_, text: string, options?: any) => {
    try {
      const service = await initializeAIService()
      return await service.polish(text, options)
    } catch (error) {
      log.error('AI polish failed:', error)
      throw error
    }
  })

  ipcMain.handle('ai:expand', async (_, text: string, options?: any) => {
    try {
      const service = await initializeAIService()
      return await service.expand(text, options)
    } catch (error) {
      log.error('AI expand failed:', error)
      throw error
    }
  })

  ipcMain.handle('ai:translate', async (_, text: string, targetLang: string, options?: any) => {
    try {
      const service = await initializeAIService()
      return await service.translate(text, targetLang, options)
    } catch (error) {
      log.error('AI translate failed:', error)
      throw error
    }
  })

  ipcMain.handle('ai:summarize', async (_, text: string, options?: any) => {
    try {
      const service = await initializeAIService()
      return await service.summarize(text, options)
    } catch (error) {
      log.error('AI summarize failed:', error)
      throw error
    }
  })

  ipcMain.handle('ai:continueWriting', async (_, text: string, context: string, options?: any) => {
    try {
      const service = await initializeAIService()
      return await service.continueWriting(text, context, options)
    } catch (error) {
      log.error('AI continue writing failed:', error)
      throw error
    }
  })

  ipcMain.handle('ai:generateContent', async (_, prompt: string, options?: any) => {
    try {
      const service = await initializeAIService()
      return await service.generateContent(prompt, options)
    } catch (error) {
      log.error('AI generate content failed:', error)
      throw error
    }
  })

  ipcMain.handle('ai:fixGrammar', async (_, text: string, options?: any) => {
    try {
      const service = await initializeAIService()
      return await service.fixGrammar(text, options)
    } catch (error) {
      log.error('AI fix grammar failed:', error)
      throw error
    }
  })

  ipcMain.handle('ai:changeTone', async (_, text: string, tone: string, options?: any) => {
    try {
      const service = await initializeAIService()
      return await service.changeTone(text, tone, options)
    } catch (error) {
      log.error('AI change tone failed:', error)
      throw error
    }
  })

  ipcMain.handle('ai:formatMarkdown', async (_, text: string) => {
    try {
      const service = await initializeAIService()
      return await service.formatMarkdown(text)
    } catch (error) {
      log.error('AI format markdown failed:', error)
      throw error
    }
  })

  ipcMain.handle('ai:extractKeywords', async (_, text: string) => {
    try {
      const service = await initializeAIService()
      return await service.extractKeywords(text)
    } catch (error) {
      log.error('AI extract keywords failed:', error)
      throw error
    }
  })

  ipcMain.handle('ai:generateOutline', async (_, topic: string, options?: any) => {
    try {
      const service = await initializeAIService()
      return await service.generateOutline(topic, options)
    } catch (error) {
      log.error('AI generate outline failed:', error)
      throw error
    }
  })

  ipcMain.handle('ai:improveSEO', async (_, text: string) => {
    try {
      const service = await initializeAIService()
      return await service.improveSEO(text)
    } catch (error) {
      log.error('AI improve SEO failed:', error)
      throw error
    }
  })

  // AI分析功能
  ipcMain.handle('ai:analyzeText', async (_, text: string, analysisType: string, options?: any) => {
    try {
      const service = await initializeAIService()
      return await service.analyzeText(text, analysisType, options)
    } catch (error) {
      log.error('AI analyze text failed:', error)
      throw error
    }
  })

  // 流式AI操作
  ipcMain.handle('ai:streamAction', async (event, action: string, text: string, options?: any) => {
    try {
      const service = await initializeAIService()
      const stream = await service.streamAIAction(action as any, { text, ...options })

      for await (const chunk of stream) {
        event.sender.send('ai:streamChunk', chunk)
      }

      event.sender.send('ai:streamEnd')
    } catch (error) {
      log.error('AI stream action failed:', error)
      event.sender.send('ai:streamError', error instanceof Error ? error.message : 'Stream failed')
    }
  })

  // AI配置管理
  ipcMain.handle('ai:getConfig', async () => {
    try {
      const service = await initializeAIService()
      return service.getConfig()
    } catch (error) {
      log.error('AI get config failed:', error)
      throw error
    }
  })

  ipcMain.handle('ai:updateConfig', async (_, config: any) => {
    try {
      const service = await initializeAIService()
      await service.updateConfig(config)
      return { success: true }
    } catch (error) {
      log.error('AI update config failed:', error)
      throw error
    }
  })

  // AI服务状态
  ipcMain.handle('ai:getStatus', async () => {
    try {
      const service = await initializeAIService()
      return {
        isConfigured: service.isConfigured(),
        availableFeatures: service.getAvailableFeatures(),
        stats: service.getServiceStats(),
      }
    } catch (error) {
      log.error('AI get status failed:', error)
      throw error
    }
  })

  ipcMain.handle('ai:testConnection', async () => {
    try {
      const service = await initializeAIService()
      return await service.testConnection()
    } catch (error) {
      log.error('AI test connection failed:', error)
      return false
    }
  })

  ipcMain.handle('ai:getAvailableFeatures', async () => {
    try {
      const service = await initializeAIService()
      return service.getAvailableFeatures()
    } catch (error) {
      log.error('AI get available features failed:', error)
      return []
    }
  })

  // AI内存功能
  ipcMain.handle('ai:storeMemory', async (_, type: string, content: string, metadata?: any, options?: any) => {
    try {
      const service = await initializeAIService()
      await service.storeMemory(type, content, { ...metadata, ...options })
      return { success: true }
    } catch (error) {
      log.error('AI store memory failed:', error)
      throw error
    }
  })

  ipcMain.handle('ai:searchMemory', async (_, query: string, limit?: number) => {
    try {
      const service = await initializeAIService()
      return await service.searchMemory(query, limit)
    } catch (error) {
      log.error('AI search memory failed:', error)
      return []
    }
  })

  ipcMain.handle('ai:getMemoryStats', async () => {
    try {
      const service = await initializeAIService()
      return service.getServiceStats()
    } catch (error) {
      log.error('AI get memory stats failed:', error)
      return null
    }
  })

  // 项目管理功能
  ipcMain.handle('ai:createProject', async (_, data: any) => {
    try {
      const service = await initializeAIService()
      const projectTool = service.getProjectTool()
      return await projectTool.execute({
        action: 'create',
        data
      })
    } catch (error) {
      log.error('AI create project failed:', error)
      throw error
    }
  })

  ipcMain.handle('ai:listProjects', async (_, filters?: any) => {
    try {
      const service = await initializeAIService()
      const projectTool = service.getProjectTool()
      return await projectTool.execute({
        action: 'list',
        data: filters
      })
    } catch (error) {
      log.error('AI list projects failed:', error)
      return []
    }
  })

  ipcMain.handle('ai:getProjectStats', async (_, projectId: string) => {
    try {
      const service = await initializeAIService()
      return service.getProjectTool().getProjectStats(projectId)
    } catch (error) {
      log.error('AI get project stats failed:', error)
      return null
    }
  })

  // AI工具获取
  ipcMain.handle('ai:getTextGenerationTool', async () => {
    try {
      const service = await initializeAIService()
      return {
        available: true,
        // 这里可以返回工具的配置信息
      }
    } catch (error) {
      log.error('AI get text generation tool failed:', error)
      return { available: false }
    }
  })

  ipcMain.handle('ai:getTextAnalysisTool', async () => {
    try {
      const service = await initializeAIService()
      return {
        available: true,
      }
    } catch (error) {
      log.error('AI get text analysis tool failed:', error)
      return { available: false }
    }
  })

  // 清理和重置
  ipcMain.handle('ai:clearCache', async () => {
    try {
      const service = await initializeAIService()
      service.getCacheStats() // 确保服务已初始化
      return { success: true }
    } catch (error) {
      log.error('AI clear cache failed:', error)
      return { success: false }
    }
  })

  ipcMain.handle('ai:reset', async () => {
    try {
      aiService = null // 重置服务实例
      const service = await initializeAIService()
      return { success: true }
    } catch (error) {
      log.error('AI reset failed:', error)
      return { success: false }
    }
  })

  log.ai('AI IPC handlers registered successfully')
}

// 导出AI服务实例（供其他模块使用）
export function getAIService(): EnhancedLangChainService | null {
  return aiService
}

// 导出AI服务初始化函数
export async function initializeAIAPI(): Promise<EnhancedLangChainService> {
  return await initializeAIService()
}